/**
* Content script of Google Checker Chrome Extension
* Author: cjls1(cjls_1@g163.com) 2012/12/02
*/

function getElementsByClassNameNew(fatherId,tagName,className){
	node = fatherId && document.getElementById(fatherId);
	if (!node) {
		return;
	}
	tagName = tagName || "*";
	className = className.split(" ");
	var classNameLength = className.length;
	for(var i=0,j=classNameLength;i<j;i++){
		className[i]= new RegExp("(^|\\s)" + className[i].replace(/\-/g, "\\-") + "(\\s|$)");
	}
	var elements = node.getElementsByTagName(tagName);
	var result = [];
	for(var i=0,j=elements.length,k=0;i<j;i++){
		var element = elements[i];
		while(className[k++].test(element.className)){
			if(k === classNameLength){
				result[result.length] = element;
				break;
			}  
		}
		k = 0;
	}
	return result;
}

var gResult;
var totalTab = 0;
var xhr = [];
var urls = [];
var secondLine = [];
var xmlHttpTimeout = [];
var urlXhrState = []; //0-sending 1-finished 2-stop 3-retry

var blackUrlBox = [
    "youtube.com",
    "facebook.com",
    "twitter.com",
    "groups.google.com"
]

var whiteUrlBox = [
    ".google.com",
    ".youku.com",
    ".chrome.com",
    ".baidu.com"
];

function urlGoodFilter(url) {
	for (var i=0; i < whiteUrlBox.length; i++) {
		if (url.indexOf(whiteUrlBox[i]) >= 0)
			return true;
	}
	return false;
}

function urlBadFilter(url) {
	for (var i=0; i < blackUrlBox.length; i++) {
		if (url.indexOf(blackUrlBox[i]) >= 0)
			return true;
	}
	return false;
}

function fillText(url, status, color) {
	return "<span class='googlecheck'> <a style='text-decoration:none;color:" 
			+ color + ";' target='googleCheck_" + (totalTab++).toString() + "' href='" 
			+ url + "'>" + status + "</a> </span>";
}

function ajaxTimeout(thisPos, secondPos){
	if (xhr[thisPos].readyState != 4 && urlXhrState[thisPos] != 1) {
		urlXhrState[thisPos] = 1;
		xhr[thisPos].abort();
		var state = "访问链接超时";
		var color = "pink";
		if (secondPos >= 0)
			secondLine[thisPos][secondPos].innerHTML += fillText(urls[thisPos], state, color);
		else
			secondLine[thisPos].innerHTML += fillText(urls[thisPos], state, color);
	}
}

var helperFunc=function(intIcint, secondLinePos, retryUrl) {
	return function() {
		if (xhr[intIcint].readyState == 4) {
			
			//stop timer first
			clearTimeout(xmlHttpTimeout[intIcint]);
			
			//finished?
			if (urlXhrState[intIcint] == 1) 
				return;
				
			var state = "可以正常访问";
			var color = " ";
			if (xhr[intIcint].status == 0) {
				state = "访问会被重置";
				color = "red";
			}
			else if (xhr[intIcint].status == 404) {
				//retry once
				if (urlXhrState[intIcint] != 3) {
					retryRequestUrl(retryUrl, intIcint, secondLinePos);
					urlXhrState[intIcint] = 3;
					return;
				}
				state = "无法找到该页";
				color = "red";
			}
			
			//set state to finished
			urlXhrState[intIcint] = 1;
			if (secondLinePos >= 0) {
				secondLine[intIcint][secondLinePos].innerHTML += fillText(urls[intIcint], state, color);
			}
			else
				secondLine[intIcint].innerHTML += fillText(urls[intIcint], state, color);
		}
	}
}
		
function requestUrl(oneUrl, pos, secondLinePos) {
	var protocol = oneUrl.split(":");
	var state = "可以正常访问";
	var color = " ";
	
	if (urlBadFilter(oneUrl) == true) {
		urlXhrState[pos] = 1;
		state = "访问会被重置";
		color = "red";
	}
	else if (/*protocol[0] == "https" ||*/ urlGoodFilter(oneUrl) == true) {
		urlXhrState[pos] = 1;
	}
	else if (protocol[0] == "ftp"){
		urlXhrState[pos] = 1;
		state = "协议暂不支持";
		color = "pink";
	}
	
	if (urlXhrState[pos] == 1) {
		if (secondLinePos >= 0)
			secondLine[pos][secondLinePos].innerHTML += fillText(oneUrl, state, color);
		else
			secondLine[pos].innerHTML += fillText(oneUrl, state, color);
	}
	else {
		//get head first by default
		urlXhrState[pos] = 0;
		xhr[pos] = new XMLHttpRequest();
		xhr[pos].open("Head", oneUrl, true);
		xhr[pos].onreadystatechange = helperFunc(pos, secondLinePos, oneUrl);
		xhr[pos].send();
		//start timer
		xmlHttpTimeout[pos] = setTimeout(ajaxTimeout, 6000, pos, secondLinePos);
	}
	return;
}

function retryRequestUrl(oneUrl, pos, secondLinePos) {
	//then try get full page
	urlXhrState[pos] = 3;
	xhr[pos] = new XMLHttpRequest();
	xhr[pos].open("GET", oneUrl, true);
	xhr[pos].onreadystatechange = helperFunc(pos, secondLinePos, oneUrl);
	xhr[pos].send();
	//start timer
	xmlHttpTimeout[pos] = setTimeout(ajaxTimeout, 6000, pos, secondLinePos);
}

function translateUrl(origUrl) {
	var finishUrl = origUrl.toString();
	
	var splitIndex1 = finishUrl.indexOf("&url=");
	if (splitIndex1 < 0)
		return finishUrl;
		
	var splitIndex2 = finishUrl.indexOf("&ei=");
	if (splitIndex2 < 0 || splitIndex1 >= splitIndex2)
		return finishUrl;
		
	finishUrl = finishUrl.substring(splitIndex1+5, splitIndex2).replace(/%2F/g,"/");
	finishUrl = finishUrl.replace(/%3A/g,":");
	
	//alert(finishUrl);
	return finishUrl;
}

chrome.extension.sendRequest(
	{target: 'background', action: 'state', tabNum: totalTab}, 
	function(response){
		localStorage['state'] = response.state;
		totalTab = response.tabid + 1;
		var enableFlag = (localStorage['state'] == 'open');
		if (enableFlag) {
			CheckBody();
		}
	});

function CheckBody() {
	gResult = getElementsByClassNameNew("ires","li","g");

	if(gResult && gResult.length > 0){
		var oneResult;
		var urlsTmp;
		var newFlag = false;
		var secondLinePos;
		//alert(gResult.length);
		for(var i=0, j=gResult.length, arrayPos = i; i<j; i++) {
			newFlag = false;
			secondLinePos = 0;
			
			//not supprot "video box" yet
			oneResult = gResult[i].getElementsByClassName("vresult");
			if (oneResult.length > 0) {
				continue;
			}
			
			secondLine[arrayPos] = gResult[i].getElementsByClassName("f kv");
			
			//special google search result, maybe news or video & googleNews
			if (secondLine[arrayPos].length == 0) {
				//news in google search
				oneResultLead = gResult[i].getElementsByClassName("vsc nulead");
				//lead news
				if (oneResultLead.length > 0) {
					newFlag = true;
					urlsTmp = oneResultLead[0].getElementsByTagName("a");
					if (urlsTmp.length > 0) {
						urls[arrayPos] = translateUrl(urlsTmp[0]);
						var newsLead = oneResultLead[0].getElementsByClassName("gl");
						if (urls[arrayPos].length > 0 && newsLead.length>0) {
							secondLine[arrayPos] = newsLead;
							requestUrl(urls[arrayPos], arrayPos, secondLinePos);
							arrayPos += 1;
						}
					}
				}
				//second news
				oneResultSec = gResult[i].getElementsByClassName("vsc nusec");
				if (oneResultSec.length > 0) {
					newFlag = true;
					for (var m=0, n=oneResultSec.length; m<n; m++) {
						urlsTmp = oneResultSec[m].getElementsByTagName("a");
						if (urlsTmp.length > 0) {
							urls[arrayPos] = translateUrl(urlsTmp[0]);
							var newsSec = oneResultSec[m].getElementsByClassName("gl");
							if (urls[arrayPos].length > 0 && newsSec.length>0) {
								secondLine[arrayPos] = newsSec;
								requestUrl(urls[arrayPos], arrayPos, secondLinePos);
								arrayPos += 1;
							}
						}
					}
				}
				if (newFlag) {
					continue;
				}
				
				//google news
				var newsJudge = gResult[i].getElementsByClassName("ts");
				secondLine[arrayPos] = gResult[i].getElementsByClassName("slp");
				if (newsJudge.length > 0 && secondLine[arrayPos].length > 0) {
					secondLinePos = 1;
					
					oneResult = gResult[i].getElementsByClassName("r");
					if (oneResult.length > 0) {
						urlsTmp = oneResult[0].getElementsByTagName("a");
						if (urlsTmp.length > 0) {
							urls[arrayPos] = translateUrl(urlsTmp[0]);
							if (urls[arrayPos].length > 0) {
								requestUrl(urls[arrayPos], arrayPos, secondLinePos);
								arrayPos += 1;
							}
						}
					}
				}
				else {
					//google inside video
					var videoJudge = 
						gResult[i].getElementsByClassName("st") || gResult[i].getElementsByClassName("vsc");
					if (videoJudge.length > 0) {
						oneResult = gResult[i].getElementsByClassName("r");
						urlsTmp = oneResult[0].getElementsByTagName("a");
						if (urlsTmp.length > 0) {
							urls[arrayPos] = translateUrl(urlsTmp[0]);
							secondLine[arrayPos] = 
								videoJudge[0].getElementsByClassName("f") || videoJudge[0].getElementsByClassName("nobr");
							requestUrl(urls[arrayPos], arrayPos, secondLinePos);
							arrayPos += 1;
							continue;
						}	
					}
				}
			}
			
			else {
				//google search
				oneResult = gResult[i].getElementsByClassName("r");
				if (oneResult.length > 0) {
					urlsTmp = oneResult[0].getElementsByTagName("a");
					if (urlsTmp.length > 0) {
						urls[arrayPos] = translateUrl(urlsTmp[0]);
						if (urls[arrayPos].length > 0) {
							requestUrl(urls[arrayPos], arrayPos, secondLinePos);
							arrayPos += 1;
						}
					}
				}

				//google inside the same site
				oneResult = gResult[i].getElementsByClassName("fc");
				if (oneResult.length > 0) {
					var urlsSec = oneResult[0].getElementsByTagName("a");
					var despSec = oneResult[0].getElementsByClassName("f");
					var urlNum = urlsSec.length -1; //remove last one
					if (despSec.length > 0 && urlNum > 0) {
						var minArgs = returnMin(despSec.length, urlNum);
						var fPos = despSec.length > urlNum && despSec.length % urlNum == 0 ? despSec.length/urlNum : 1;
						for (var k=0, l=fPos-1; k < minArgs; k++, l += fPos) {
							urls[arrayPos] = translateUrl(urlsSec[k]);
							secondLine[arrayPos] = despSec[l];
							requestUrl(urls[arrayPos], arrayPos, -1);
							arrayPos += 1;
						}
					}
				}
			}
		}
	}
	
	return;
}

function returnMin(a, b) {
	if (a < b) {
		return a;
	}
	return b;
}
